﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CRM.DataAccess.Entities;
using CRM.Business.Services;
using CRM.Encryption;
using System.Data;
using Telerik.Web.UI;
using System.Configuration;
using System.Globalization;

namespace Web.Invoice
{
    public partial class ViewInvoice : System.Web.UI.Page
    {
        static USER user;
        static long? assignedToID = null;
        static string prevPage = String.Empty;
        static int rowIndex = 0;
        static double[,] arr;
        static int size;
        static ROLE r;
        static string requestEdit = string.Empty;
        static long InvID;
        static string itemID = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
                return;
            assignedToID = null;
            if (Request.UrlReferrer != null)
            {
                prevPage = Request.UrlReferrer.ToString();
                hdntxtPrevPage.Value = prevPage;
            }
            user = (USER)Session["User"];
            if (user != null)
            {
                rowIndex = 0;
                r = RoleService.GetRoleByID((long)user.ROLE_ID);
                if ((!(bool)user.IS_ADMIN) && (!(bool)r.IS_MANAGER))
                {
                    assignedToID = user.ID;
                    divAssignTo.Visible = false;
                }

                requestEdit = Request.QueryString["id"];
                if (requestEdit != null)
                {
                    InvID = Convert.ToInt64(requestEdit);
                    LoadInvoiceInfo(Convert.ToInt64(requestEdit));
                    hdntxtInvoiceID.Value = requestEdit;
                    hdntxtPrint.Value = "0";
                }
            }
        }
        private void LoadInvoiceInfo(long invoiceID)
        {
            INVOICE_DETAIL invoiceDetail = InvoiceService.GetInvoiceDetailByID(invoiceID, assignedToID);

            if (invoiceDetail != null)
            {
                itemID = invoiceDetail.ITEM_ID.ToString();
                ////Invoice Details
                txtOrganizationName.Text = invoiceDetail.ORGANIZATION_NAME;
                txtContactName.Text = invoiceDetail.CONTACT_NAME;
                txtCustomerNo.Text = invoiceDetail.CUSTOMER_NO;
                if (invoiceDetail.STATUS_ID != null)
                {
                    INVOICE_STATUS istatus = InvoiceService.GetInvoiceStatusByID(invoiceDetail.STATUS_ID);
                    if (istatus != null)
                        txtStatus.Text = istatus.STATUS_NAME;
                }
                txtInvoiceDate.Text = invoiceDetail.INVOICE_DATE.ToString();
                txtDueDate.Text = invoiceDetail.DUE_DATE.ToString();
                txtPurchaseOrder.Text = invoiceDetail.PURCHASE_ORDER;
                txtSalesCommission.Text = invoiceDetail.SALES_COMMISSION.ToString();
                txtAssignedTo.Text = invoiceDetail.ASSIGN_TO;
                //////Adress Detail
                txtOfficeAddress.Text = invoiceDetail.OFFICE_ADDRESS;
                txtHomeAddress.Text = invoiceDetail.HOME_ADDRESS;
                txtOfficePOBox.Text = invoiceDetail.OFFICE_PO_BOX;
                txtHomePOBox.Text = invoiceDetail.HOME_PO_BOX;
                txtOfficeCity.Text = invoiceDetail.OFFICE_CITY;
                txtHomeCity.Text = invoiceDetail.HOME_CITY;
                txtOfficeState.Text = invoiceDetail.OFFICE_STATE;
                txtHomeState.Text = invoiceDetail.HOME_STATE;
                txtOfficePostalCode.Text = invoiceDetail.OFFICE_POSTAL_CODE;
                txtHomePostalCode.Text = invoiceDetail.HOME_POSTAL_CODE;
                txtOfficeCountry.Text = invoiceDetail.OFFICE_COUNTRY;
                txtHomeCountry.Text = invoiceDetail.HOME_COUNTRY;
                //Terms & Conditions
                if (invoiceDetail.TERMS_CONDITIONS_ID != null)
                {
                    TERMS_AND_CONDITIONS tac = TermsAndConditionsService.GetTACByID(Convert.ToInt64(invoiceDetail.TERMS_CONDITIONS_ID));
                    if (tac != null)
                        txtTermsAndConditions.Text = tac.DESCRIPTION;
                }

                //Description Details
                if (invoiceDetail.DESCRIPTION_ID != null)
                {
                    DESCRIPTION_DETAILS dd = DescriptionDetailService.GetDescriptionByID(Convert.ToInt64(invoiceDetail.DESCRIPTION_ID));
                    if (dd != null)
                        txtDescriptions.Text = dd.DESCRIPTION;
                }
                //Item Details
                if (ViewState["Products"] == null)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add(new DataColumn("ID"));
                    dt.Columns.Add(new DataColumn("ITEM_ID"));
                    dt.Columns.Add(new DataColumn("ITEM_DETAIL_ID"));
                    dt.Columns.Add(new DataColumn("ProductID"));
                    dt.Columns.Add(new DataColumn("ProductName"));
                    dt.Columns.Add(new DataColumn("ProductDescription"));
                    dt.Columns.Add(new DataColumn("GST", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("Quantity", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("Balance", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("CurrentBalance", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("Image"));
                    dt.Columns.Add(new DataColumn("UnitPrice", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("DiscountPrice", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("DiscountPercent", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("TotalPrice", typeof(System.Double)));
                    dt.Columns.Add(new DataColumn("DiscountType"));
                    ViewState["Products"] = GetItemListDataTable(invoiceDetail.ITEM_ID, dt);
                    rowIndex = dt.Rows.Count;
                }
            }
            else
            {
                divContent.Style["display"] = "none";
                divError.Style["display"] = "block";

            }
        }
        private DataTable GetItemListDataTable(long? itemID, DataTable dt)
        {
            List<ITEM_DETAILS> itemDetails = ItemService.GetListItemDetailByItemID(itemID);
            if (itemDetails != null)
            {
                size = itemDetails.Count;
                arr = new double[2, size];
                for (int i = 0; i < size; i++)
                {
                    arr[0, i] = itemDetails[i].PRODUCT_ID;
                    arr[1, i] = Convert.ToDouble(itemDetails[i].QUANTITY.ToString());
                }
                for (int i = 0; i < size; i++)
                {
                    for (int j = i + 1; j < size; j++)
                    {
                        if (arr[0, i] == arr[0, j])
                        {
                            arr[1, i] += arr[1, j];
                            arr[1, j] = 0;
                        }
                    }
                }
                rowIndex = itemDetails.Count;
                for (int i = 0; i < itemDetails.Count; i++)
                {
                    ITEM_DETAILS item = itemDetails[i];
                    DataRow dr = dt.NewRow();
                    dr["ID"] = i;
                    dr["ITEM_ID"] = item.ITEM_ID;
                    dr["ITEM_DETAIL_ID"] = item.ITEM_DETAIL_ID;
                    dr["ProductID"] = item.PRODUCT_ID.ToString();
                    dr["ProductDescription"] = item.DESCRIPTION;
                    dr["GST"] = item.GST_PERCENT == null ? 0 : item.GST_PERCENT;
                    dr["ProductName"] = item.PRODUCT_NAME;
                    dr["Quantity"] = item.QUANTITY;
                    dr["Balance"] = item.BALANCE + arr[1, i];
                    dr["CurrentBalance"] = item.BALANCE + arr[1, i] - item.QUANTITY;
                    dr = updatevalue(dr, dt);
                    dr["Image"] = item.IMAGE;
                    dr["UnitPrice"] = item.UNIT_PRICE;
                    dr["DiscountPrice"] = item.DISCOUNT_PRICE;
                    dr["DiscountPercent"] = item.DISCOUNT_PERCENT;
                    if (item.DISCOUNT_PERCENT != 0)
                        dr["DiscountType"] = "Per";
                    else if (item.DISCOUNT_PRICE != 0)
                        dr["DiscountType"] = "Pri";
                    else
                        dr["DiscountType"] = "Per";
                    dr["TotalPrice"] = item.PRICE;
                    dt.Rows.Add(dr);
                }
            }
            return dt;
        }
        protected void RadGrid1_ItemDataBound(object sender, GridItemEventArgs e)
        {
            DataTable dt = (DataTable)ViewState["Products"];
            if (e.Item is GridDataItem)
            {
                GridDataItem item = e.Item as GridDataItem;
                System.Web.UI.WebControls.Image img = (System.Web.UI.WebControls.Image)item.FindControl("productImage");
                TextBox txtProductName = (TextBox)item.FindControl("txtProductName");
                TextBox txtProductDescription = (TextBox)item.FindControl("txtProductDescription");
                RadButton rbtnPercent = (RadButton)item.FindControl("rbtnPercent");
                RadNumericTextBox rntxtGST = (RadNumericTextBox)item.FindControl("rntxtGST");
                RadNumericTextBox rntxtUnitPrice = (RadNumericTextBox)item.FindControl("rntxtUnitPrice");
                RadButton rbtnPrice = (RadButton)item.FindControl("rbtnPrice");
                RadNumericTextBox rntxtQuantity = (RadNumericTextBox)item.FindControl("rntxtQuantity");
                RadNumericTextBox rntxtBalance = (RadNumericTextBox)item.FindControl("rntxtBalance");
                RadNumericTextBox rntxtCurrentBalance = (RadNumericTextBox)item.FindControl("rntxtCurrentBalance");
                Panel divDiscountPercent = (Panel)item.FindControl("divDiscountPercent");
                Panel divDiscountPrice = (Panel)item.FindControl("divDiscountPrice");
                RadNumericTextBox rntxtDiscountPercent = (RadNumericTextBox)item.FindControl("rntxtDiscountPercent");
                RadNumericTextBox rntxtDiscountPrice = (RadNumericTextBox)item.FindControl("rntxtDiscountPrice");
                RadNumericTextBox rntxtTotalPrice = (RadNumericTextBox)item.FindControl("rntxtTotalPrice");
                /////////////////////////
                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["ID"].ToString() == item.GetDataKeyValue("ID").ToString())
                    {
                        img.ImageUrl = dr["Image"].ToString();
                        txtProductDescription.Text = dr["ProductDescription"].ToString();
                        rntxtGST.Value = convertCurrencyToDouble(dr["GST"].ToString());
                        rntxtUnitPrice.Value = convertCurrencyToDouble(dr["UnitPrice"].ToString());

                        rbtnPrice.Checked = dr["DiscountType"].ToString() == "Pri" ? true : false;
                        rbtnPercent.Checked = dr["DiscountType"].ToString() == "Per" ? true : false;
                        rntxtQuantity.Value = Convert.ToDouble(dr["Quantity"].ToString());
                        rntxtBalance.Value = Convert.ToDouble(dr["Balance"].ToString());
                        rntxtCurrentBalance.Value = Convert.ToDouble(dr["CurrentBalance"].ToString());
                        rntxtDiscountPrice.Value = Convert.ToDouble(dr["DiscountPrice"].ToString());
                        rntxtDiscountPercent.Value = Convert.ToDouble(dr["DiscountPercent"].ToString());
                        if (dr["DiscountType"].ToString() == "Per")
                        {
                            divDiscountPercent.Style.Add("display", "block");
                            divDiscountPrice.Style.Add("display", "none");
                        }
                        else if (dr["DiscountType"].ToString() == "Pri")
                        {
                            divDiscountPercent.Style.Add("display", "none");
                            divDiscountPrice.Style.Add("display", "block");
                        }
                        rntxtTotalPrice.Value = Convert.ToDouble(dr["TotalPrice"].ToString());
                        // sum += rntxtTotalPrice.Value;
                        break;
                    }
                }
            }
            else if (e.Item is GridFooterItem)
            {
                double? sum = 0;
                GridFooterItem footer = (GridFooterItem)e.Item;
                RadNumericTextBox footeritem = (footer["TotalPrice"].FindControl("rntxtTotalPriceFooter") as RadNumericTextBox);
                if (footeritem != null)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        sum += Convert.ToDouble(dr["TotalPrice"].ToString());
                    }
                    footeritem.Value = sum;
                }
            }
        }
        private double? convertCurrencyToDouble(string str)
        {
            if (str != "")
                return Double.Parse(str, NumberStyles.AllowCurrencySymbol | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, new CultureInfo("en-US"));
            return 0;
        }
        private double? getTotalPrice(double? unitprice, double? quantity, double? discountper, double? discountpri, double? gst)
        {
            double? total = 0;
            total = unitprice * quantity;
            total += total * gst / 100.0;
            if (discountper != null)
                total -= total * discountper / 100.0;
            else if (discountpri != null)
                total -= discountpri;
            if (total < 0) total = 0;
            return total;
        }
        private DataRow updatevalue(DataRow dr, DataTable dt)
        {
            if (dt != null)
            {
                for (int i = Convert.ToInt32(dr["ID"].ToString()) - 1; i >= 0; i--)
                {
                    if (dt.Rows[i]["ProductID"].ToString() == dr["ProductID"].ToString())
                    {
                        dr["Balance"] = Convert.ToDouble(dt.Rows[i]["CurrentBalance"]);
                        dr["CurrentBalance"] = Convert.ToDouble(dr["Balance"].ToString()) - Convert.ToDouble(dr["Quantity"].ToString());
                        break;
                    }
                }
            }
            return dr;
        }
        protected void RadGrid1_ItemCreated(object sender, GridItemEventArgs e)
        {
            if (e.Item is GridPagerItem)
            {
                GridPagerItem oGridPagerItem = (GridPagerItem)e.Item;
                RadComboBox oRadComboBox = (RadComboBox)oGridPagerItem.FindControl("PageSizeComboBox");
                oRadComboBox.Width = Unit.Pixel(50);
            }
           
        }
        protected void RadGrid1_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
        {
            DataTable dt = (DataTable)ViewState["Products"];
            RadGrid1.DataSource = dt;
        }
      
    }
}